import request from '@/utils/request'
import { onMounted, ref } from 'vue'

export type FetchOptions = {
  method?: 'POST' | 'GET'

  manual?: boolean
  defaultParams?: Record<string, any>
  headers?: Record<string, any>

  onAfter?: (res: any) => any
  onSuccess?: (res: any, params: any) => any
}

export default <TData>(
  url: string,
  { defaultParams, manual, method = 'GET', headers, onAfter, onSuccess }: FetchOptions = {},
) => {
  const loading = ref(false)
  const data = ref<TData>()

  const execute = async (params: any) => {
    try {
      loading.value = true
      let res = await request(url, method, { data: params, headers })
      res = onAfter ? onAfter(res) : res
      data.value = res
      onSuccess?.(res, params)
    } catch (err) {
      console.error(err)
    } finally {
      loading.value = false
    }
  }

  const run = (params?: any) => execute(params)

  onMounted(() => {
    if (!manual) {
      execute(defaultParams)
    }
  })

  return {
    data,
    loading,
    run,
  }
}
